"""
oyMDDTools by Erkan Ozgur Yilmaz (c) 2010

v10.7.8

Description :
-------------
For now the script exports the given objects to MDD file format with their
animations

Version History :
-----------------
10.7.8
- added info print outs

10.5.17
- modifications for Maya 2011 and Pymel 1.0.2

10.4.22
- fixed time shift in files exported from Maya and opened in Houdini
- fixed missing frames issue for files exported from Maya and opened in Houdini

10.4.21
- initial working version

TODO List:
----------
"""

import pymel.core as pm
import struct
#from struct import pack



__version__ = '10.7.8'



def exportMDD( objList, filePath, startFrame, endFrame, fps=25.0 ):
    '''exports the given objects to mdd file format
    the function is mainly ported from Blender
    '''
    
    numOfVertices = 0
    shapes = []
    
    # get all the vertices of all the meshes
    for obj in objList:
        shape = obj.getShape()
        shapes.append( shape )
        numOfVertices += shape.numVertices()
    
    
    numOfFrames = endFrame - startFrame + 1
    fps = float(fps)
    
    print "numOfObjects  :", len(objList)
    print "numOfVertices :", numOfVertices
    print "numOfFrames   :", numOfFrames
    print "fps           :", fps
    
    mddFile = open( filePath, 'wb' )
    
    # write the header
    mddFile.write( struct.pack(">2i", numOfFrames, numOfVertices) )
    
    # write the frame times
    # correction for houdini, frame numbers are shifted in houdini
    timeData = [float(frame-1)/fps for frame in range(startFrame, endFrame + 1)]
    mddFile.write( struct.pack(">%df" % (numOfFrames), *timeData) )
    
    print "timeData :"
    print "----------"
    print timeData
    
    
    for frame in range(startFrame - 1, endFrame + 1):
        # set the currentTime
        pm.currentTime( frame )
        data = [axis for shape in shapes for v in shape.getPoints(space='kWorld') for axis in v.get()[:3] ]
        try:
            mddFile.write(struct.pack(">%df" % (numOfVertices * 3 ), *data ))
        except struct.error as detail:
            print len(data)
            raise struct.error(detail)
    
    mddFile.close()
    
    print 'MDD Exported: %s frames: %d' % (filePath, numOfFrames )